import argparse
from collections import Counter

import mysql.connector



cnx = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="music"
)


def recent_collections(userId):
    cursor = cnx.cursor(dictionary=True)
    sql="""
    select c.songId,s.tags
    from collect c
    join song s on c.songId =s.id
    where c.userId = %s AND c.isDelete = 0 AND s.isDelete = 0
    order by c.createTime DESC
    limit 5;
    """
    cursor.execute(sql,(userId,))
    result = cursor.fetchall()
    cursor.close()
    return result

def all_songs():
    cursor = cnx.cursor(dictionary=True)
    sql="""
    select id ,tags
    from song
    where isDelete=0
    """
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    return result

def recommend(userId,num):
    collects = recent_collections(userId)
    songs = all_songs()

    # print('collects : ',collects)
    # print('songs: ',songs)

    # step2: get tags
    tags =[]
    for song in collects:
        tags.extend(song['tags'].split(','))

    # print('tags: ',tags)

    # step3: tag weights
    tag_weights = Counter(tags)
    # print('tag_weights: ',tag_weights)

    # step4: 计算相似度
    recommendations = []
    for song in songs:
        score = sum(tag_weights[tag] for tag in song['tags'].split(',') if tag in tag_weights)
        recommendations.append((song['id'],score))

    # step5: sort by score
    recommendations.sort(key=lambda x:x[1],reverse=True)
    # print('recommendations: ', recommendations)
    return [song for song,score in recommendations[:num]]



if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Music recommender')

    # Required arguments
    parser.add_argument('-i', '--id', help='userId', type=int, required=True)
    parser.add_argument('-n', '--num', help='the number of return', type=int, required=True)

    args = parser.parse_args()

    ret = recommend(args.id,args.num)

    result = ",".join([str(num) for num in ret])
    print(result)
